package com.mathdroid.gui.main.filter;

import java.awt.Color;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;

import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;

import com.mathdroid.gui.ImageLoader;

/**
 * This custom renderer shows an icon for an item source filter and a checkbox
 * with the source name.
 */
public final class FilterCellRenderer 
extends JPanel 
implements ListCellRenderer {

	/**
	 * Default UID.
	 */
	private static final long serialVersionUID = 1L;
	
	/**
	 * A selectable filter.
	 */
	private JCheckBox checkBox = new JCheckBox();
	
	/**
	 * A label that just has an image icon.
	 */
	private JLabel icon = new JLabel();
	
	/**
	 * The component constraints used in this cell.
	 */
	private final GridBagConstraints c = new GridBagConstraints();
	
	/**
	 * The spacing between components.
	 */
	private static final int SPACING = 10;

	/**
	 * The yellow-green droid color.
	 */
	private static final Color DROID_GREEN = new Color(172, 230, 52);
	
	/**
	 * The image loader.
	 */
	private final ImageLoader il = new ImageLoader();

	@Override
	public Component getListCellRendererComponent(
			final JList list, final Object value,
			final int index, final boolean isSelected, 
			final boolean cellHasFocus) {

		this.setLayout(new GridBagLayout());
		
		FilterElement element = (FilterElement) value;
		
		if (element.isEnabled()) {
			this.icon.setIcon(
					this.il.getEnabledFilterImage(element.getIcon()));
		} else {
			this.icon.setIcon(
					this.il.getDisabledFilterImage(element.getIcon()));
		}

		this.c.gridx = 0;
		this.c.gridy = 0;
		this.c.insets = new Insets(SPACING, SPACING, SPACING, SPACING);
		this.c.weightx = 0;
		this.c.anchor = GridBagConstraints.WEST;
		this.add(this.icon, this.c);
		
		if (isSelected) {
			this.setBackground(DROID_GREEN);
			this.checkBox.setBackground(DROID_GREEN);
		} else {
			this.setBackground(Color.WHITE);
			this.checkBox.setBackground(Color.WHITE);
		}
		
		this.checkBox.setText(element.toString());
		this.checkBox.setSelected(element.isEnabled());
		this.c.gridx = 1;
		this.c.gridy = 0;
		this.c.insets = new Insets(SPACING, 0, SPACING, SPACING);
		this.c.weightx = 1;
		this.add(this.checkBox, this.c);
		
		return this;
	}

}
